'use strict';
(function () {
    if (window.$hybrid) {
        console.log('$hybrid already exists!!!');
        return;
    }

    let $hybrid = {};
    let cbid = 2147483647;

    function genCbid() {
        let id = cbid--;
        if (cbid == 0) cbid = 2147483647;
        return id;
    }

    $hybrid.err = function (err) {
        console.error(err);
    }

    /**
     * 注册js函数，供java调用
     */
    $hybrid.register = function (name, func) {
        let functions = this.functions || {};
        functions[name] = func;
        this.functions = functions;
    };

    /**
     * 处理java调用js函数
     */
    $hybrid.invoke = function (name, data, cbid) {
        let func = this.functions[name];
        if (typeof func === 'function') {
            func(data, function (resp) {
                let res = 'hybrid://callback?cbid=' + cbid;
                if (resp) {
                    res = res + '&cb_data=' + encodeURIComponent(resp);
                }
                $hybrid.channel.src = res;
            });
        }
    };

    /**
     * 调用java函数
     */
    $hybrid.call = function (name, data, callback) {
        if (!name) return;

        let res = 'hybrid://invoke?fname=' + name;

        if (data) {
            res = res + '&data=' + encodeURIComponent(data);
        }

        if (typeof callback === 'function') {
            if (!this.callbacks) {
                this.callbacks = {};
            }
            let cbid = genCbid();
            this.callbacks[cbid] = callback;
            res = res + '&cbid=' + cbid;
        }
        $hybrid.channel.src = res;
    };

    /**
     * java函数回调js的
     */
    $hybrid.callback = function (cbid, data) {
        let callback = this.callbacks[cbid];
        if (typeof callback === 'function') {
            callback(data);
            delete this.callbacks[cbid];
        }
    };

    let channel = document.createElement('iframe');
    channel.style.display = 'none';
    document.documentElement.appendChild(channel);
    $hybrid.channel = channel;

    window.$hybrid = $hybrid;

    let readyEvent = document.createEvent('Events');
    readyEvent.initEvent('HybridReady');
    readyEvent.$hybrid = $hybrid;
    document.dispatchEvent(readyEvent);
})();